package com.cnzz.site1255174697.fragment;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import com.alibaba.baichuan.android.trade.AlibcTradeSDK;
import com.cnzz.site1255174697.R;
import com.cnzz.site1255174697.factory.GoodsFactory;
import com.cnzz.site1255174697.factory.IndexFactory;
import com.cnzz.site1255174697.holder.GoodsCellHolder;
import com.cnzz.site1255174697.holder.GoodsObjectHolder;
import com.cnzz.site1255174697.holder.MallTopHolder;
import com.cnzz.site1255174697.model.BannerEntity;
import com.cnzz.site1255174697.model.BaseEntity;
import com.cnzz.site1255174697.model.GoodsTagEntity;
import com.cnzz.site1255174697.model.MallListEntity;
import com.cnzz.site1255174697.model.MallObjectEntity;
import com.cnzz.site1255174697.model.MallTopEntity;
import com.cnzz.site1255174697.model.MallTuiEntity;
import com.cqyanyu.yanyu.db.XDB;
import com.cqyanyu.yanyu.http.XCallback;
import com.cqyanyu.yanyu.http.XResultList;
import com.cqyanyu.yanyu.view.recyclerView.YRecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页--单独推荐页面
 */
@SuppressLint("ValidFragment")
public class MallIndexFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, YRecyclerView.OnLoadMoreListener, View.OnClickListener {

    protected YRecyclerView mRecyclerView;
    protected ImageButton fab;
    private String pid;
    protected int page = 1;//当前页
    private View view;
    public static Map<String, String> map = new HashMap<>();
    public static Map<String, MallTuiEntity.DataBean.ItemsBean.XItemBean> maplItem = new HashMap<>();

    public MallIndexFragment(String pid) {
        this.pid = pid;
    }

    private MallTopEntity mallTopEntity = new MallTopEntity();
    List<MallListEntity> resultList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.base_list, null);
        initView();
        mRecyclerView.bindItemHolder(MallTopEntity.class, MallTopHolder.class);
        mRecyclerView.bindItemHolder(MallTuiEntity.DataBean.ItemsBean.XItemBean.class, GoodsCellHolder.class);
        mRecyclerView.setSpanCount(2);
        mRecyclerView.setCellSpanCount(MallTopEntity.class, 2);
        mRecyclerView.addHeader(mallTopEntity);
        mRecyclerView.setRefreshing(true);
        loadData();
        initData();
        return view;
    }

    private void initView() {
        fab = (ImageButton) view.findViewById(R.id.fab);
        mRecyclerView = (YRecyclerView) view.findViewById(R.id.mRecyclerView);
        mRecyclerView.setOnLoadMoreListener(this);
        mRecyclerView.setOnRefreshListener(this);
        fab.setOnClickListener(this);
    }

    //获取详情
    public void loadData() {
        mRecyclerView.setRefreshing(true);
        IndexFactory.getGoodsList(getActivity(), pid, "3", "", new XCallback<List<MallListEntity>>() {
            @Override
            public void onSuccess(List<MallListEntity> result) {
                resultList = result;
                for (MallListEntity mallListEntity : result) {
                    map.put(mallListEntity.getGoods_id(), mallListEntity.getAction_url());
                }
                loadInfo(result, listToString(result));
            }

            @Override
            public void onFinished() {
                mRecyclerView.setRefreshing(false);
            }
        });
    }

    //获取详情列表
    private void loadInfo(final List<MallListEntity> list, String ids) {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        try {
            jsonObject1.put("fields", "title,nick,pic_url,cid,price,post_fee,promoted_service,ju,shop_name");
            jsonObject2.put("num_iids", ids);
            jsonObject3.put("page_no", page);
            jsonArray.put(jsonObject1);
            jsonArray.put(jsonObject2);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        if (list.size() == 1) {
//            mRecyclerView.bindItemHolder(MallObjectEntity.class, GoodsObjectHolder.class);
//            GoodsFactory.getGoodsOneInfo(getActivity(), "tae.items.list", jsonArray.toString(), new Callback.CommonCallback<MallObjectEntity>() {
//                @Override
//                public void onSuccess(MallObjectEntity result) {
//                    List<MallObjectEntity> list1 = new ArrayList<MallObjectEntity>();
//                    list1.add(result);
//                    mRecyclerView.setData(list1);
//                }
//                @Override
//                public void onError(Throwable ex, boolean isOnCallback) {
//                }
//                @Override
//                public void onCancelled(CancelledException cex) {
//                }
//                @Override
//                public void onFinished() {
//                }
//            });
//        } else {
        GoodsFactory.getGoodsInfo(getActivity(), "tae.items.list", jsonArray.toString(), new Callback.CommonCallback<MallTuiEntity>() {
            @Override
            public void onSuccess(MallTuiEntity result) {
                for (MallTuiEntity.DataBean.ItemsBean.XItemBean x : result.getData().getItems().getX_item()) {
                    maplItem.put(x.getOpen_id(), x);
                }
                List<MallTuiEntity.DataBean.ItemsBean.XItemBean> listItemsBean = new ArrayList<MallTuiEntity.DataBean.ItemsBean.XItemBean>();
                for (int i = 0; i < resultList.size(); i++) {
                    MallTuiEntity.DataBean.ItemsBean.XItemBean obj = maplItem.get(resultList.get(i).getGoods_id());
                    if (obj != null) {
                        listItemsBean.add(maplItem.get(resultList.get(i).getGoods_id()));
                    }
                }
                mRecyclerView.setData(listItemsBean);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
                mRecyclerView.setRefreshing(false);
                mRecyclerView.loadFinish();
            }
        });
//        }
    }

    /**
     * 把list转换为一个用逗号分隔的字符串
     */
    private String listToString(List<MallListEntity> list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i).getGoods_id() + ",");
                } else {
                    sb.append(list.get(i).getGoods_id());
                }
            }
        }
        return sb.toString();
    }

    //顶部数据
    private void initData() {
        if (page == 1) {
            IndexFactory.getBanner(getActivity(), "", new XCallback<List<BannerEntity>>() {
                @Override
                public void onSuccess(List<BannerEntity> result) {
                    mallTopEntity.setAdvsEntities(result);
                    mRecyclerView.notifyDataSetChanged();
                }

                @Override
                public void onFinished() {
                }
            });
            //分类
            IndexFactory.getIndexTop(getActivity(), pid, new XCallback<XResultList<BaseEntity>>() {
                @Override
                public void onSuccess(XResultList<BaseEntity> result) {
                    mallTopEntity.setKindsEntityList(result.data);
                    mRecyclerView.notifyDataSetChanged();
                }

                public void onFinished() {
                }
            });
            IndexFactory.getBanner(getActivity(), "2", new XCallback<List<BannerEntity>>() {
                @Override
                public void onSuccess(List<BannerEntity> result) {
                    mallTopEntity.setBannerEntityList(result);
                    mRecyclerView.notifyDataSetChanged();
                }

                @Override
                public void onFinished() {
                }
            });
            IndexFactory.getGoodsTag(getActivity(), pid, new XCallback<List<GoodsTagEntity>>() {
                @Override
                public void onSuccess(List<GoodsTagEntity> result) {
                    mallTopEntity.setKindsTagList(result);
                    mRecyclerView.notifyDataSetChanged();
                }

                @Override
                public void onFinished() {
                }
            });
            IndexFactory.getTag(getActivity(), new XCallback<XResultList<BaseEntity>>() {
                @Override
                public void onSuccess(XResultList<BaseEntity> result) {
                    mallTopEntity.setTagList(result.data);
                    mRecyclerView.notifyDataSetChanged();
                }

                @Override
                public void onFinished() {
                }
            });
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        loadData();
        initData();
    }

    @Override
    public void onLoadMore() {
        page += 1;
        loadData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AlibcTradeSDK.destory();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.fab) {
            mRecyclerView.getRecyclerView().smoothScrollToPosition(0);
        }
    }
}
